﻿using UnityEngine;
using UnityEngine.EventSystems;

namespace Jinndev {

    public class PointerClickHelper : MonoBehaviour, IPointerClickHandler, IPointerDownHandler, IPointerUpHandler, IPointerEnterHandler, IPointerExitHandler, IBeginDragHandler, IEndDragHandler, IDragHandler {

        public System.Action<PointerEventData> onPointerClick;
        public System.Action<PointerEventData> onPointerDown;
        public System.Action<PointerEventData> onPointerUp;
        public System.Action<PointerEventData> onPointerEnter;
        public System.Action<PointerEventData> onPointerExit;

        [Tooltip("拖拽时是否允许点击")]
        public bool enableWhileDragging = false;
        [Tooltip("指针离开时是否自动抬起")]
        public bool pointerUpWhileExit = false;

        public bool dragging { get; private set; }
        public bool pointerDown { get; private set; }

        public void OnPointerClick(PointerEventData eventData) {
            if (!enableWhileDragging && dragging) {
                return;
            }
            onPointerClick?.Invoke(eventData);
        }

        public void OnPointerDown(PointerEventData eventData) {
            if (!enableWhileDragging && dragging) {
                return;
            }
            pointerDown = true;
            onPointerDown?.Invoke(eventData);
        }

        public void OnPointerUp(PointerEventData eventData) {
            if (!enableWhileDragging && dragging) {
                return;
            }
            pointerDown = false;
            onPointerUp?.Invoke(eventData);
        }

        public void OnPointerEnter(PointerEventData eventData) {
            onPointerEnter?.Invoke(eventData);
        }

        public void OnPointerExit(PointerEventData eventData) {
            onPointerExit?.Invoke(eventData);
            if (pointerUpWhileExit && pointerDown) {
                OnPointerUp(eventData);
            }
        }

        public void OnBeginDrag(PointerEventData eventData) {
            
        }

        public void OnEndDrag(PointerEventData eventData) {
            dragging = false;
        }

        public void OnDrag(PointerEventData eventData) {
            // 必须有此接口，否则OnBeginDrag和OnEndDrag不执行
            dragging = true;
        }

    }

}
